package com.guazai.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guazai.common.pojo.UserInterfaceInfo;
import com.guazai.project.common.ErrorCode;
import com.guazai.project.exception.BusinessException;
import com.guazai.project.mapper.UserInterfaceInfoMapper;
import com.guazai.project.model.dto.userinterfaceinfo.UserInterfaceInfoQueryRequest;
import com.guazai.project.model.vo.UserInterfaceInfoVO;
import com.guazai.project.service.UserInterfaceInfoService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description 用户接口信息服务实现类
 * @author guazai
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService {

    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    /**
     * 判断参数是否正确
     *
     * @param userInterfaceInfo
     * @param add
     */
    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 创建时，所有参数必须非空
        if (add) {
            if (userInterfaceInfo.getInterfaceId() <= 0 || userInterfaceInfo.getUserId() <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口或用户不存在");
            }
        }
        if (userInterfaceInfo.getLeftNum() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余次数不能小于 0");
        }
    }

    /**
     * user_interfaceInfo表调用次数自增
     *
     * @param interfaceInfoId
     * @param userId
     * @return
     */
    @Override
    public boolean invokeCount(long interfaceInfoId, long userId) {
        //判断参数是否正确
        if (userId < 0 || interfaceInfoId < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //如果数据库中有这条数据，就修改---totalInvokes = totalInvokes + 1  leftNum = leftNum - 1
        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("userId", userId);
        updateWrapper.eq("interfaceInfoId", interfaceInfoId);
        updateWrapper.setSql("totalInvokes = totalInvokes + 1, leftNum = leftNum - 1");
        if(!this.update(updateWrapper)) {
            //如果没有，加插入数据---userId  interfaceInfoId  totalInvokes = 1  leftNum = 99，直接返回调用结果
            UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
            userInterfaceInfo.setUserId(userId);
            userInterfaceInfo.setInterfaceId(interfaceInfoId);
            userInterfaceInfo.setTotalInvokes(1);
            userInterfaceInfo.setLeftNum(99);
            return userInterfaceInfoMapper.insert(userInterfaceInfo) > 0;
        } else {
            return true;
        }
    }

    /**
     * 分页查询userInterfaceInfo并以VO返回
     *
     * @param request
     * @return
     */
    public Page<UserInterfaceInfoVO> listUserInterfaceInfoVOByPage(UserInterfaceInfoQueryRequest request) {
        //限制爬虫
        if (request.getPageSize() > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //分页查询条件封装
        Page<UserInterfaceInfo> page = new Page<>(request.getCurrent(), request.getPageSize());
        QueryWrapper<UserInterfaceInfo> wrapper = getQueryWrapper(request);
        //查询
        userInterfaceInfoMapper.selectPage(page, wrapper);
        List<UserInterfaceInfo> records = page.getRecords();
        //如果查询结果为空，则返回一个空记录的Page<UserVO>
        Page<UserInterfaceInfoVO> userVOPage = new Page<>();
        if (CollectionUtils.isEmpty(records)) {
            userVOPage.setRecords(new ArrayList<>());
            return userVOPage;
        }
        //把结果映射成UserVO
        List<UserInterfaceInfoVO> result = records.stream().map(this::getUserInterfaceInfoVO).collect(Collectors.toList());
        userVOPage.setRecords(result);
        return userVOPage;
    }

    /**
     * 得到查询条件wrapper
     *
     * @param request
     * @return
     */
    private static QueryWrapper<UserInterfaceInfo> getQueryWrapper(UserInterfaceInfoQueryRequest request) {
        QueryWrapper<UserInterfaceInfo> wrapper = new QueryWrapper<>();
        Long id = request.getId();
        Long userId = request.getUserId();
        Long interfaceId = request.getInterfaceId();
        Integer status = request.getStatus();
        //String sortField = request.getSortField();
        //String sortOrder = request.getSortOrder();
        wrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        wrapper.eq(ObjectUtils.isNotEmpty(interfaceId), "interfaceId", interfaceId);
        wrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        wrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        wrapper.eq("isDelete", false);
        return wrapper;
    }

    /**
     * 将userInterfaceInfo转为VO对象
     * @param userInterfaceInfo
     * @return
     */
    public UserInterfaceInfoVO getUserInterfaceInfoVO(UserInterfaceInfo userInterfaceInfo) {
        // 转为vo对象
        UserInterfaceInfoVO userInterfaceInfoVO = UserInterfaceInfoVO.objToVo(userInterfaceInfo);
        return userInterfaceInfoVO;
    }

    /**
     * 分页查询登录用户自己的用户与接口调用信息
     * @param request
     * @return
     */
    @Override
    public Page<UserInterfaceInfoVO> listMyUserInterfaceInfoVOByPage(UserInterfaceInfoQueryRequest request) {
        //限制爬虫
        if (request.getPageSize() > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //分页查询条件封装
        Page<UserInterfaceInfo> page = new Page<>(request.getCurrent(), request.getPageSize());
        QueryWrapper<UserInterfaceInfo> wrapper = getQueryWrapper(request);
        //查询
        userInterfaceInfoMapper.selectPage(page, wrapper);
        List<UserInterfaceInfo> records = page.getRecords();
        //如果查询结果为空，则返回一个空记录的Page<UserVO>
        Page<UserInterfaceInfoVO> userVOPage = new Page<>();
        if (CollectionUtils.isEmpty(records)) {
            userVOPage.setRecords(new ArrayList<>());
            return userVOPage;
        }
        //把结果映射成UserVO
        List<UserInterfaceInfoVO> result = records.stream().map(this::getUserInterfaceInfoVO).collect(Collectors.toList());
        userVOPage.setRecords(result);
        return userVOPage;
    }
}




